import requests
from typing import Dict, Optional, List, Union, Any, Callable
import json
import re
import logging
import time
import random
from datetime import datetime
from functools import wraps

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('qpet_api.log'),
        logging.StreamHandler()
    ]
)

# 重试装饰器
def retry(max_retries=3, delay=1, backoff=2, exceptions=(Exception,)):
    """
    重试装饰器，用于自动重试可能失败的网络请求
    
    Args:
        max_retries: 最大重试次数
        delay: 初始延迟时间（秒）
        backoff: 延迟倍数
        exceptions: 捕获的异常类型
    """
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            mtries, mdelay = max_retries, delay
            while mtries > 0:
                try:
                    return func(*args, **kwargs)
                except exceptions as e:
                    mtries -= 1
                    if mtries == 0:
                        raise
                    
                    logging.warning(f"请求失败: {str(e)}，{mdelay}秒后重试...")
                    time.sleep(mdelay)
                    mdelay *= backoff
            return func(*args, **kwargs)
        return wrapper
    return decorator

class QPetAPIClient:
    def __init__(self, cookie: str = "", headers: Optional[Dict[str, str]] = None):
        """
        初始化API客户端
        
        Args:
            cookie: 用户cookie
            headers: 可选的额外请求头
        """
        self.base_url = "https://fight.pet.qq.com/cgi-bin/petpk"
        self.cookie = cookie
        self.qq = ""
        self.nickname = ""
        self.is_logged_in = False
        self.session = requests.Session()  # 使用会话保持连接
        self.request_interval = 1.0  # 请求间隔时间（秒）
        self.last_request_time = 0  # 上次请求时间
        
        # 设置默认请求头
        self.headers = {
            "authority": "fight.pet.qq.com",
            "accept": "application/json, text/plain, */*",
            "accept-language": "zh-CN,zh;q=0.9",
            "cookie": cookie,
            "referer": "https://fight.pet.qq.com/",
            "sec-ch-ua": '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": '"Windows"',
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
            "x-requested-with": "XMLHttpRequest"
        }
        
        # 如果提供了额外的请求头，则更新
        if headers:
            self.headers.update(headers)
            
        # 如果提供了cookie，尝试解析获取QQ号
        if cookie:
            self._extract_info_from_cookie()
            self._verify_login()
    
    def __del__(self):
        """析构函数，关闭会话"""
        try:
            self.session.close()
        except:
            pass
    
    def _rate_limit(self):
        """
        实现请求速率限制
        确保两次请求之间有一定的间隔，避免请求过快
        """
        current_time = time.time()
        time_elapsed = current_time - self.last_request_time
        
        if time_elapsed < self.request_interval:
            sleep_time = self.request_interval - time_elapsed
            time.sleep(sleep_time)
        
        self.last_request_time = time.time()
    
    @retry(max_retries=3, delay=2, exceptions=(requests.RequestException,))
    def _request(self, method: str, url: str, **kwargs) -> requests.Response:
        """
        发送HTTP请求的通用方法
        
        Args:
            method: 请求方法（GET、POST等）
            url: 请求URL
            **kwargs: 其他请求参数
            
        Returns:
            Response: HTTP响应对象
        """
        # 应用速率限制
        self._rate_limit()
        
        # 记录请求信息
        logging.debug(f"发送{method}请求: {url}")
        if kwargs.get('params'):
            logging.debug(f"请求参数: {kwargs.get('params')}")
        
        # 添加随机延迟，模拟真实用户行为
        time.sleep(random.uniform(0.5, 1.5))
        
        # 发送请求
        response = self.session.request(
            method,
            url,
            headers=self.headers,
            timeout=30,  # 设置超时时间
            **kwargs
        )
        
        # 检查响应状态
        response.raise_for_status()
        
        # 记录响应信息
        logging.debug(f"响应状态码: {response.status_code}")
        
        return response
    
    def _extract_info_from_cookie(self) -> None:
        """从Cookie中提取QQ号等信息"""
        try:
            # 从cookie中提取uin参数（QQ号）
            uin_match = re.search(r'uin=o(\d+)', self.cookie)
            if uin_match:
                self.qq = uin_match.group(1)
                logging.info(f"从Cookie提取QQ号: {self.qq}")
            
            # 从cookie中提取昵称
            nick_match = re.search(r'qqgame_nick=([^;]+)', self.cookie)
            if nick_match:
                self.nickname = nick_match.group(1)
                logging.info(f"从Cookie提取昵称: {self.nickname}")
        except Exception as e:
            logging.error(f"从Cookie提取信息失败: {str(e)}")
    
    def _verify_login(self) -> bool:
        """验证登录状态"""
        try:
            # 使用获取个人信息接口验证是否登录
            params = {
                "cmd": "getdata",
                "op": "getpkinfo"
            }
            
            response = self._request(
                "GET",
                self.base_url,
                params=params
            )
            
            result = response.json()
            if result.get("code") == 0:
                self.is_logged_in = True
                logging.info("登录状态验证成功")
                return True
            else:
                self.is_logged_in = False
                logging.warning(f"登录状态验证失败: {result.get('msg')}")
                return False
        except Exception as e:
            self.is_logged_in = False
            logging.error(f"验证登录状态时出错: {str(e)}")
            return False
    
    def login(self, qq: str, password: str) -> Dict:
        """
        登录Q宠大乐斗
        
        Args:
            qq: QQ号
            password: QQ密码
            
        Returns:
            Dict: 登录结果，包含状态和消息
        """
        try:
            # 构造登录请求参数
            login_url = "https://fight.pet.qq.com/cgi-bin/petlogin"
            login_params = {
                "uin": qq,
                "password": password,
                "logintype": "1",  # 使用QQ号密码登录
                "appid": "102067279",
                "s_url": "https://fight.pet.qq.com/"
            }
            
            # 发送登录请求
            login_response = self._request(
                "POST",
                login_url,
                data=login_params,
                headers={
                    "User-Agent": self.headers["user-agent"],
                    "Referer": "https://fight.pet.qq.com/login.html"
                },
                allow_redirects=False  # 不自动跟随重定向，以便获取响应头中的Cookie
            )
            
            # 检查重定向状态码
            if login_response.status_code in [301, 302]:
                # 从响应头中获取所有设置的Cookie
                cookies = login_response.cookies
                cookie_str = '; '.join([f"{name}={value}" for name, value in cookies.items()])
                
                # 更新客户端的Cookie
                self.cookie = cookie_str
                self.headers["cookie"] = cookie_str
                self.session.cookies.update(cookies)
                
                # 提取信息
                self._extract_info_from_cookie()
                
                # 验证登录状态
                if self._verify_login():
                    return {
                        "status": "success",
                        "message": "登录成功",
                        "qq": self.qq,
                        "nickname": self.nickname
                    }
                else:
                    return {
                        "status": "error",
                        "message": "登录成功但验证状态失败"
                    }
            else:
                # 登录请求失败
                error_msg = login_response.text
                return {
                    "status": "error",
                    "message": f"登录请求失败: {error_msg}"
                }
                
        except Exception as e:
            logging.error(f"登录过程中出现错误: {str(e)}")
            return {
                "status": "error",
                "message": f"登录过程中出现错误: {str(e)}"
            }
    
    def update_cookie(self, cookie: str) -> bool:
        """
        更新Cookie
        
        Args:
            cookie: 新的Cookie值
            
        Returns:
            bool: 更新是否成功
        """
        try:
            self.cookie = cookie
            self.headers["cookie"] = cookie
            
            # 清除会话中的旧Cookie，设置新Cookie
            self.session.cookies.clear()
            for cookie_part in cookie.split(';'):
                if '=' in cookie_part:
                    name, value = cookie_part.strip().split('=', 1)
                    self.session.cookies.set(name, value)
            
            self._extract_info_from_cookie()
            return self._verify_login()
        except Exception as e:
            logging.error(f"更新Cookie失败: {str(e)}")
            return False
    
    def get_user_info(self) -> Dict:
        """
        获取用户信息
        
        Returns:
            Dict: 用户信息，包括等级、经验值、金币等
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
            
        params = {
            "cmd": "getdata",
            "op": "getuserinfo"
        }
        
        response = self._request(
            "GET",
            self.base_url,
            params=params
        )
        
        return response.json()
    
    def get_pet_info(self) -> Dict:
        """
        获取宠物信息
        
        Returns:
            Dict: 宠物信息，包括等级、属性、技能等
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
            
        params = {
            "cmd": "getdata",
            "op": "getpetinfo"
        }
        
        response = self._request(
            "GET",
            self.base_url,
            params=params
        )
        
        return response.json()
    
    def daily_sign(self) -> Dict:
        """
        执行每日签到
        
        Returns:
            Dict: 签到结果
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
            
        params = {
            "cmd": "dailysign",
            "op": "sign"
        }
        
        response = self._request(
            "GET",
            self.base_url,
            params=params
        )
        
        return response.json()
    
    def get_daily_gift(self, cmd: str, op: str, key: str) -> Dict:
        """
        获取每日礼包
        
        Args:
            cmd: 命令参数
            op: 操作参数
            key: 密钥参数
            
        Returns:
            Dict: API响应结果
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
            
        params = {
            "cmd": cmd,
            "op": op,
            "key": key
        }
        
        response = self._request(
            "GET",
            self.base_url,
            params=params
        )
        
        return response.json()
    
    def get_daily_tasks(self) -> Dict:
        """
        获取每日任务列表
        
        Returns:
            Dict: 每日任务列表
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
            
        params = {
            "cmd": "task",
            "op": "getlist",
            "type": "daily"
        }
        
        response = self._request(
            "GET",
            self.base_url,
            params=params
        )
        
        return response.json()
    
    def complete_task(self, task_id: str) -> Dict:
        """
        完成指定任务
        
        Args:
            task_id: 任务ID
            
        Returns:
            Dict: 任务完成结果
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
            
        params = {
            "cmd": "task",
            "op": "complete",
            "taskid": task_id
        }
        
        response = self._request(
            "GET",
            self.base_url,
            params=params
        )
        
        return response.json()
    
    def pet_battle(self, target_id: str, skill_id: str = "") -> Dict:
        """
        执行宠物对战
        
        Args:
            target_id: 对战目标ID
            skill_id: 使用的技能ID（可选）
            
        Returns:
            Dict: 对战结果
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
            
        params = {
            "cmd": "battle",
            "op": "start",
            "targetid": target_id
        }
        
        # 如果提供了技能ID，则添加到参数中
        if skill_id:
            params["skillid"] = skill_id
        
        response = self._request(
            "GET",
            self.base_url,
            params=params
        )
        
        return response.json()
    
    def get_battle_list(self, battle_type: str = "normal") -> Dict:
        """
        获取对战列表
        
        Args:
            battle_type: 对战类型，如normal（普通）、arena（竞技场）等
            
        Returns:
            Dict: 对战列表
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
            
        params = {
            "cmd": "battle",
            "op": "getlist",
            "type": battle_type
        }
        
        response = self._request(
            "GET",
            self.base_url,
            params=params
        )
        
        return response.json()
    
    def use_item(self, item_id: str, target_id: str = "") -> Dict:
        """
        使用道具
        
        Args:
            item_id: 道具ID
            target_id: 目标ID（可选，某些道具需要指定目标）
            
        Returns:
            Dict: 使用道具结果
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
            
        params = {
            "cmd": "item",
            "op": "use",
            "itemid": item_id
        }
        
        # 如果提供了目标ID，则添加到参数中
        if target_id:
            params["targetid"] = target_id
        
        response = self._request(
            "GET",
            self.base_url,
            params=params
        )
        
        return response.json()
    
    def get_item_list(self) -> Dict:
        """
        获取道具列表
        
        Returns:
            Dict: 道具列表
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
            
        params = {
            "cmd": "item",
            "op": "getlist"
        }
        
        response = self._request(
            "GET",
            self.base_url,
            params=params
        )
        
        return response.json()
    
    def feed_pet(self, food_id: str) -> Dict:
        """
        喂养宠物
        
        Args:
            food_id: 食物ID
            
        Returns:
            Dict: 喂养结果
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
            
        params = {
            "cmd": "pet",
            "op": "feed",
            "foodid": food_id
        }
        
        response = self._request(
            "GET",
            self.base_url,
            params=params
        )
        
        return response.json()
    
    def auto_battle(self, count: int = 5) -> List[Dict]:
        """
        自动执行多次对战
        
        Args:
            count: 对战次数
            
        Returns:
            List[Dict]: 所有对战结果列表
        """
        if not self.is_logged_in:
            return [{"code": -1, "msg": "未登录或登录已过期"}]
        
        results = []
        
        # 获取对战列表
        battle_list = self.get_battle_list()
        if battle_list.get("code") != 0:
            return [{"code": -1, "msg": "获取对战列表失败", "data": battle_list}]
        
        # 获取可对战目标列表
        targets = battle_list.get("data", {}).get("list", [])
        if not targets:
            return [{"code": -1, "msg": "没有可对战的目标"}]
        
        # 执行多次对战
        for i in range(min(count, len(targets))):
            target_id = targets[i].get("id")
            if target_id:
                result = self.pet_battle(target_id)
                results.append(result)
        
        return results
        
    def get_shop_items(self, shop_type: str = "normal") -> Dict:
        """
        获取商店物品列表
        
        Args:
            shop_type: 商店类型，如normal（普通）、special（特殊）等
            
        Returns:
            Dict: 商店物品列表
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
            
        params = {
            "cmd": "shop",
            "op": "getlist",
            "type": shop_type
        }
        
        response = self._request(
            "GET",
            self.base_url,
            params=params
        )
        
        return response.json()
    
    def buy_item(self, item_id: str, count: int = 1) -> Dict:
        """
        购买商店物品
        
        Args:
            item_id: 物品ID
            count: 购买数量
            
        Returns:
            Dict: 购买结果
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
            
        params = {
            "cmd": "shop",
            "op": "buy",
            "itemid": item_id,
            "count": count
        }
        
        response = self._request(
            "GET",
            self.base_url,
            params=params
        )
        
        return response.json()
    
    def get_friend_list(self) -> Dict:
        """
        获取好友列表
        
        Returns:
            Dict: 好友列表
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
            
        params = {
            "cmd": "friend",
            "op": "getlist"
        }
        
        response = self._request(
            "GET",
            self.base_url,
            params=params
        )
        
        return response.json()
    
    def add_friend(self, friend_id: str) -> Dict:
        """
        添加好友
        
        Args:
            friend_id: 好友ID
            
        Returns:
            Dict: 添加结果
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
            
        params = {
            "cmd": "friend",
            "op": "add",
            "friendid": friend_id
        }
        
        response = self._request(
            "GET",
            self.base_url,
            params=params
        )
        
        return response.json()
    
    def gift_friend(self, friend_id: str, gift_id: str) -> Dict:
        """
        赠送礼物给好友
        
        Args:
            friend_id: 好友ID
            gift_id: 礼物ID
            
        Returns:
            Dict: 赠送结果
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
            
        params = {
            "cmd": "friend",
            "op": "gift",
            "friendid": friend_id,
            "giftid": gift_id
        }
        
        response = self._request(
            "GET",
            self.base_url,
            params=params
        )
        
        return response.json()
    
    def get_skill_list(self) -> Dict:
        """
        获取可学习的技能列表
        
        Returns:
            Dict: 技能列表
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
            
        params = {
            "cmd": "skill",
            "op": "getlist"
        }
        
        response = self._request(
            "GET",
            self.base_url,
            params=params
        )
        
        return response.json()
    
    def learn_skill(self, skill_id: str) -> Dict:
        """
        学习技能
        
        Args:
            skill_id: 技能ID
            
        Returns:
            Dict: 学习结果
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
            
        params = {
            "cmd": "skill",
            "op": "learn",
            "skillid": skill_id
        }
        
        response = self._request(
            "GET",
            self.base_url,
            params=params
        )
        
        return response.json()
    
    def upgrade_skill(self, skill_id: str) -> Dict:
        """
        升级技能
        
        Args:
            skill_id: 技能ID
            
        Returns:
            Dict: 升级结果
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
            
        params = {
            "cmd": "skill",
            "op": "upgrade",
            "skillid": skill_id
        }
        
        response = self._request(
            "GET",
            self.base_url,
            params=params
        )
        
        return response.json()
    
    def get_arena_info(self) -> Dict:
        """
        获取竞技场信息
        
        Returns:
            Dict: 竞技场信息
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
            
        params = {
            "cmd": "arena",
            "op": "getinfo"
        }
        
        response = self._request(
            "GET",
            self.base_url,
            params=params
        )
        
        return response.json()
    
    def arena_battle(self, target_id: str) -> Dict:
        """
        进行竞技场战斗
        
        Args:
            target_id: 对手ID
            
        Returns:
            Dict: 战斗结果
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
            
        params = {
            "cmd": "arena",
            "op": "battle",
            "targetid": target_id
        }
        
        response = self._request(
            "GET",
            self.base_url,
            params=params
        )
        
        return response.json()
    
    def upgrade_pet(self, attribute: str) -> Dict:
        """
        升级宠物属性
        
        Args:
            attribute: 属性名，如str（力量）、agi（敏捷）、int（智力）等
            
        Returns:
            Dict: 升级结果
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
            
        params = {
            "cmd": "pet",
            "op": "upgrade",
            "attr": attribute
        }
        
        response = self._request(
            "GET",
            self.base_url,
            params=params
        )
        
        return response.json()
    
    def auto_daily_tasks(self) -> Dict:
        """
        自动完成所有每日任务
        
        Returns:
            Dict: 完成任务的结果汇总
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
        
        results = {
            "status": "success",
            "completed_tasks": [],
            "failed_tasks": []
        }
        
        # 1. 获取每日任务列表
        tasks = self.get_daily_tasks()
        if tasks.get("code") != 0:
            results["status"] = "error"
            results["message"] = "获取任务列表失败"
            return results
        
        # 2. 尝试完成每个任务
        task_list = tasks.get("data", {}).get("list", [])
        for task in task_list:
            task_id = task.get("id")
            task_name = task.get("name", "未知任务")
            
            # 跳过已完成的任务
            if task.get("completed"):
                results["completed_tasks"].append({
                    "id": task_id,
                    "name": task_name,
                    "status": "已完成"
                })
                continue
            
            # 尝试完成任务
            result = self.complete_task(task_id)
            
            if result.get("code") == 0:
                results["completed_tasks"].append({
                    "id": task_id,
                    "name": task_name,
                    "status": "完成成功",
                    "reward": result.get("data", {}).get("reward")
                })
            else:
                results["failed_tasks"].append({
                    "id": task_id,
                    "name": task_name,
                    "status": "完成失败",
                    "message": result.get("msg")
                })
            
            # 添加延迟，避免请求过快
            time.sleep(1)
        
        return results
    
    def auto_daily_routine(self) -> Dict:
        """
        自动执行每日例行任务
        
        Returns:
            Dict: 执行结果汇总
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
        
        results = {
            "status": "success",
            "steps": []
        }
        
        # 1. 签到
        try:
            sign_result = self.daily_sign()
            results["steps"].append({
                "name": "每日签到",
                "status": "成功" if sign_result.get("code") == 0 else "失败",
                "details": sign_result
            })
        except Exception as e:
            results["steps"].append({
                "name": "每日签到",
                "status": "异常",
                "error": str(e)
            })
        
        # 2. 领取每日礼包
        try:
            gift_result = self.get_daily_gift("dailygift", "draw", "login")
            results["steps"].append({
                "name": "每日礼包",
                "status": "成功" if gift_result.get("code") == 0 else "失败",
                "details": gift_result
            })
        except Exception as e:
            results["steps"].append({
                "name": "每日礼包",
                "status": "异常",
                "error": str(e)
            })
        
        # 3. 自动对战
        try:
            battle_results = self.auto_battle(5)  # 进行5次对战
            success_count = sum(1 for r in battle_results if r.get("code") == 0)
            results["steps"].append({
                "name": "自动对战",
                "status": "完成",
                "success_count": success_count,
                "total_count": len(battle_results)
            })
        except Exception as e:
            results["steps"].append({
                "name": "自动对战",
                "status": "异常",
                "error": str(e)
            })
        
        # 4. 完成每日任务
        try:
            tasks_result = self.auto_daily_tasks()
            results["steps"].append({
                "name": "每日任务",
                "status": tasks_result["status"],
                "completed": len(tasks_result.get("completed_tasks", [])),
                "failed": len(tasks_result.get("failed_tasks", []))
            })
        except Exception as e:
            results["steps"].append({
                "name": "每日任务",
                "status": "异常",
                "error": str(e)
            })
        
        return results
    
    def export_cookie(self) -> str:
        """
        导出当前Cookie
        
        Returns:
            str: 当前Cookie字符串
        """
        return self.cookie
    
    def save_cookie_to_file(self, filename: str = "qpet_cookie.txt") -> bool:
        """
        将当前Cookie保存到文件
        
        Args:
            filename: 文件名
            
        Returns:
            bool: 是否保存成功
        """
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                f.write(self.cookie)
            logging.info(f"Cookie已保存到文件: {filename}")
            return True
        except Exception as e:
            logging.error(f"保存Cookie到文件失败: {str(e)}")
            return False
    
    @classmethod
    def load_from_file(cls, filename: str = "qpet_cookie.txt") -> 'QPetAPIClient':
        """
        从文件加载Cookie并创建客户端实例
        
        Args:
            filename: Cookie文件名
            
        Returns:
            QPetAPIClient: API客户端实例
        """
        try:
            with open(filename, 'r', encoding='utf-8') as f:
                cookie = f.read().strip()
            
            client = cls(cookie)
            if client.is_logged_in:
                logging.info(f"从文件{filename}加载Cookie成功")
                return client
            else:
                logging.warning(f"从文件{filename}加载Cookie，但登录验证失败")
                return client
        except Exception as e:
            logging.error(f"从文件加载Cookie失败: {str(e)}")
            return cls()  # 返回一个未登录的实例
    
    def set_request_interval(self, seconds: float) -> None:
        """
        设置请求间隔时间
        
        Args:
            seconds: 间隔秒数
        """
        self.request_interval = max(0.5, seconds)  # 最小0.5秒
        logging.info(f"请求间隔时间已设置为{self.request_interval}秒")
        
    def get_timestamp(self) -> int:
        """
        获取当前时间戳
        
        Returns:
            int: 当前时间戳（秒）
        """
        return int(time.time())
    
    def generate_report(self) -> Dict:
        """
        生成账号状态报告
        
        Returns:
            Dict: 账号状态报告
        """
        if not self.is_logged_in:
            return {"code": -1, "msg": "未登录或登录已过期"}
        
        report = {
            "timestamp": self.get_timestamp(),
            "date": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "account": {
                "qq": self.qq,
                "nickname": self.nickname
            },
            "status": {}
        }
        
        # 获取用户信息
        try:
            user_info = self.get_user_info()
            if user_info.get("code") == 0:
                user_data = user_info.get("data", {})
                report["status"]["user"] = {
                    "level": user_data.get("level"),
                    "exp": user_data.get("exp"),
                    "money": user_data.get("money"),
                    "energy": user_data.get("energy")
                }
        except Exception as e:
            report["status"]["user"] = {"error": str(e)}
        
        # 获取宠物信息
        try:
            pet_info = self.get_pet_info()
            if pet_info.get("code") == 0:
                pet_data = pet_info.get("data", {})
                report["status"]["pet"] = {
                    "name": pet_data.get("name"),
                    "level": pet_data.get("level"),
                    "hp": pet_data.get("hp"),
                    "attack": pet_data.get("attack"),
                    "defense": pet_data.get("defense")
                }
        except Exception as e:
            report["status"]["pet"] = {"error": str(e)}
        
        # 添加其他状态信息
        
        return report 